package cn.edu.zafu.bigdata.x.yaojy;

import java.io.*;
import java.util.Scanner;

public class FileReadWrite {
    public static void writeToFile(String fileName, String content) {
        File file = new File("files/yaojy/" + fileName);
        File dir = new File("files/yaojy/");
        if (!dir.exists()){
            dir.mkdir();
        }

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))){
            writer.write(content);
            System.out.println("写入成功！");
        }catch (IOException e){
            System.err.println("写入文件是发生错误：" + e.getMessage());
        }
    }

    public static void readFromFile(String fileName) {
        File file = new File("files/yaojy/" + fileName);

        try (BufferedReader reader = new BufferedReader(new FileReader(file))){
            String line;
            StringBuilder content = new StringBuilder();
            while ((line = reader.readLine()) != null){
                content.append(line).append("\n");
            }
            System.out.println("文件内容如下：\n" + content.toString().trim());
        }catch (IOException e){
            System.err.println("写入文件是发生错误：" + e.getMessage());
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("请输入文件名（学号，如2022010101.txt）：");
        String fileName = scanner.nextLine();

        System.out.print("请输入要写入文件的文本内容：");
        StringBuilder content = new StringBuilder();
        String line;
        while (!(line = scanner.nextLine()).isEmpty()) {
            content.append(line).append("\n");
        }

        writeToFile(fileName, content.toString().trim());

        readFromFile(fileName);

        scanner.close();
    }

}
